package com.prb.controller;

import com.prb.service.ResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("/login")
public class LoginController {

    public static Set<String> userDb = new HashSet<>();


    @Autowired
    ResumeService resumeService;

    static {

        userDb.add("zhangSan");
        userDb.add("lssi");
        userDb.add("wangwu");
    }

    @RequestMapping("/page")
    public String login(){

        System.out.println("login page");
        return "login";
    }

    @PostMapping("/do")
    public ModelAndView doLogin(HttpServletRequest request , HttpServletResponse response , String userName , String password){

        ModelAndView mv = new ModelAndView();

        if (!userDb.contains(userName)) {
            mv.addObject("code" , "error");
            mv.addObject("msg" , "login fail");
            mv.setViewName("login");
        }else{
            String token = UUID.randomUUID().toString();
            response.setHeader("token" , token);
            Cookie cookie = new Cookie("token" , token);
            response.addCookie(cookie);

            request.getSession().setAttribute("token" , token);

            mv.addObject("code" , "success");
            mv.addObject("msg" , "login success");
            mv.addObject("data" , resumeService.listResume());
            mv.setViewName("resume");
        }

        return mv;
    }


}
